<template>
  <!-- 主内容区 -->
  <div class="task-publish-container" v-loading="loading">
    <!-- 页面标题 -->
    <div class="header-section">
      <h2 class="page-title">任务发布</h2>
      <p class="page-subtitle">发布CAAC考核任务或行业应用任务给学生</p>
    </div>

    <!-- 发布新任务卡片 -->
    <el-card class="task-card mb-4">
      <div slot="header" class="card-header">
        <span>发布新任务</span>
        <span class="card-subtitle">创建测试任务或考核任务</span>
      </div>

      <el-form :model="taskForm" :rules="rules" ref="taskForm" label-width="100px" class="task-form">
        <el-row :gutter="20">
          <!-- 任务类型 -->
          <el-col :span="12">
            <el-form-item label="任务类型" prop="name" required>
              <el-select
                v-model="taskForm.name"
                placeholder="请选择或输入任务类型"
                style="width: 100%"
                filterable
                allow-create
                default-first-option
              >
                <el-option :label="item.name" :value="item.name" v-for="item in taskList" />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 目标班级 -->
          <el-col :span="12">
            <el-form-item label="目标班级" prop="deptId" required>
              <el-select
                v-model="taskForm.deptId"
                placeholder="请选择班级"
                style="width: 100%"
              >
                <el-option v-for="item in deptList" :label="item.deptName" :value="item.deptId" />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 截止时间 -->
          <el-col :span="12">
            <el-form-item label="截止时间" prop="endTime" required>
              <el-date-picker
                v-model="taskForm.endTime"
                type="datetime"
                placeholder="请选择截止时间"
                style="width: 100%"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>

          <!-- 任务描述 -->
          <el-col :span="24">
            <el-form-item label="任务描述" prop="des" required>
              <el-input
                v-model="taskForm.des"
                type="textarea"
                :rows="4"
                placeholder="详细描述任务要求、评分标准等"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 发布按钮 -->
        <div class="form-actions">
          <el-button type="primary" @click="publishTask">
            <i class="fa fa-plus-circle mr-2"></i> 发布任务
          </el-button>
        </div>
      </el-form>
    </el-card>

    <!-- 已发布任务卡片 -->
    <el-card class="task-card mb-4">
      <div slot="header" class="card-header">
        <span>已发布任务</span>
        <span class="card-subtitle">管理您发布的所有任务</span>
      </div>

      <div class="app-container" v-if="taskList">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="任务" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入任务"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="任务状态" prop="taskstatus">
            <el-select v-model="queryParams.taskstatus" placeholder="请选择任务状态" clearable filterable size="small">
              <el-option
                v-for="dict in taskstatusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-has-role="['teacher']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-has-role="['teacher']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-has-role="['teacher']"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="任务id" align="center" prop="id" />
          <el-table-column label="任务" align="center" prop="name" />
          <el-table-column label="任务表述" align="center" prop="des" />
          <el-table-column label="任务状态" align="center" prop="taskstatus" :formatter="taskstatusFormat" />
          <el-table-column label="开始时间" align="center" prop="createTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="结束时间" align="center" prop="endTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-has-role="['teacher']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-has-role="['teacher']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改任务列表对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
          <el-form ref="taskForm" :model="taskForm" :rules="rules" label-width="80px">
            <el-form-item label="任务" prop="name">
              <el-input v-model="taskForm.name" placeholder="请输入任务" />
            </el-form-item>
            <el-form-item label="任务表述" prop="des">
              <el-input v-model="taskForm.des" placeholder="请输入任务表述" />
            </el-form-item>
            <el-form-item label="任务状态">
              <el-radio-group v-model="taskForm.taskstatus">
                <el-radio
                  v-for="dict in taskstatusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker clearable size="small"
                              v-model="taskForm.endTime"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="选择结束时间">
              </el-date-picker>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </div>

      <!-- 空状态显示 -->
      <div class="empty-state" v-else>
        <div class="empty-icon">
          <i class="fa fa-inbox fa-2x"></i>
        </div>
        <h4 class="empty-title">暂无已发布的任务</h4>
        <p class="empty-description">您还没有发布任何任务，点击"发布任务"按钮创建您的第一个任务</p>
      </div>
    </el-card>

    <!-- 任务模板卡片 -->
    <el-card class="task-card">
      <div slot="header" class="card-header">
        <span>任务模板</span>
        <span class="card-subtitle">常用的任务模板，快速创建相似任务</span>
      </div>

      <!-- 模板网格 -->
      <div class="template-grid">
        <!-- 模板1 -->
        <div class="template-item">
          <h4 class="template-title">CAAC基础飞行考核</h4>
          <p class="template-description">包含起飞、悬停、降落等基础操作的标准考核</p>
          <el-button type="text" @click="useTemplate('CAAC基础飞行考核')">
            使用模板 <i class="fa fa-arrow-right ml-1 text-xs"></i>
          </el-button>
        </div>

        <!-- 模板2 -->
        <div class="template-item">
          <h4 class="template-title">森林巡检任务</h4>
          <p class="template-description">模拟森林环境下的巡检飞行任务</p>
          <el-button type="text" @click="useTemplate('森林巡检任务')">
            使用模板 <i class="fa fa-arrow-right ml-1 text-xs"></i>
          </el-button>
        </div>

        <!-- 模板3 -->
        <div class="template-item">
          <h4 class="template-title">海域搜救演练</h4>
          <p class="template-description">海上救援场景下的应急飞行训练</p>
          <el-button type="text" @click="useTemplate('海域搜救演练')">
            使用模板 <i class="fa fa-arrow-right ml-1 text-xs"></i>
          </el-button>
        </div>

        <!-- 模板4 -->
        <div class="template-item">
          <h4 class="template-title">精准投放任务</h4>
          <p class="template-description">训练精准定位物品投放的操控技能</p>
          <el-button type="text" @click="useTemplate('精准投放任务')">
            使用模板 <i class="fa fa-arrow-right ml-1 text-xs"></i>
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import {addTask, delTask, exportTask, getTask, listTask, updateTask} from "@/api/task/task";
import {parseTime} from "@/utils/neu";
import {listDept} from "@/api/system/dept";

export default {
  name: 'TaskPublish',
  data() {
    return {
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 遮罩层
      loading: true,
      // 任务列表表格数据
      taskList: [],
      // 任务状态字典
      taskstatusOptions: [],
      // 班级列表
      deptList: [],
      taskForm: {
        id: null,
        name: null,
        des: null,
        taskstatus: 0,
        createTime: null,
        endTime: null,
        deptId: null,
      },
      rules: {
        name: [
          { required: true, message: '请选择任务类型', trigger: 'change' }
        ],
        deptId: [
          { required: true, message: '请选择目标班级', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择截止时间', trigger: 'change' }
        ],
        des: [
          { required: true, message: '请输入任务描述', trigger: 'blur' }
        ]
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        taskstatus: null,
      },
    }
  },
  methods: {
    // 表单重置
    reset() {
      this.taskForm = {
        id: null,
        name: null,
        des: null,
        taskstatus: 0,
        createTime: null,
        endTime: null,
        deptId: null,
      };
      this.resetForm("taskForm");
    },
    // 任务状态字典翻译
    taskstatusFormat(row, column) {
      return this.selectDictLabel(this.taskstatusOptions, row.taskstatus);
    },
    getDateDiff(date1, date2, unit = 'd') {
      // 转换为 Date 对象
      const d1 = new Date(date1);
      const d2 = new Date(date2);

      // 校验日期有效性
      if (isNaN(d1.getTime()) || isNaN(d2.getTime())) {
        throw new Error('无效的日期格式');
      }

      // console.log(d1.getTime(), d2.getTime())

      // 计算毫秒差值
      const diffMs = d1.getTime() - d2.getTime();

      // 根据单位转换
      const units = {
        ms: 1,
        s: 1000,
        m: 1000 * 60,
        h: 1000 * 60 * 60,
        d: 1000 * 60 * 60 * 24
      };

      return Math.floor(diffMs / units[unit]);
    },
    parseTime,
    publishTask() {
      this.$refs.taskForm.validate((valid) => {
        if (valid) {
          // 发布任务的逻辑
          this.$message.success('任务发布成功');
          addTask(this.taskForm).then(response => {
            this.msgSuccess("新增成功");
            this.reset();
            this.getList();
          });
        } else {
          this.$message.error('请填写所有必填项');
          return false;
        }
      });
    },
    useTemplate(templateName) {
      // 使用模板的逻辑
      this.$message.info(`使用模板: ${templateName}`);
    },
    getList() {
      this.loading = true;
      listTask(this.queryParams).then(response => {
        response.rows.forEach(item => {
          if (item.createTime > item.endTime) {
            item.taskstatus = "0"
            return
          }
          const dateDiff = this.getDateDiff(item.endTime, new Date(), 's');
          if (dateDiff > 0) {
            item.taskstatus = "1"
          } else {
            item.taskstatus = "2"
          }
        });
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      listDept().then(response => {
        this.deptList = response.data;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTask(id).then(response => {
        this.taskForm = response.data;
        this.open = true;
        this.title = "修改任务列表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["taskForm"].validate(valid => {
        if (valid) {
          if (this.taskForm.id != null) {
            updateTask(this.taskForm).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除任务列表编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delTask(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有任务列表数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return exportTask(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    }

  },
  created() {
    this.getList()
    this.getDicts("task_status").then(response => {
      this.taskstatusOptions = response.data;
    });
  }
}
</script>

<style scoped>
.task-publish-container {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.header-section {
  margin-bottom: 32px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #272E3B;
  margin-bottom: 8px;
}

.page-subtitle {
  color: #86909C;
  margin: 0;
}

.task-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-subtitle {
  font-size: 14px;
  color: #86909C;
}

.task-form {
  margin-top: 20px;
}

.form-actions {
  text-align: left;
  padding-top: 10px;
}

.empty-state {
  text-align: center;
  padding: 48px 0;
}

.empty-icon {
  margin-bottom: 16px;
  color: #C9CDD4;
}

.empty-title {
  font-size: 16px;
  font-weight: 500;
  color: #4E5969;
  margin-bottom: 8px;
}

.empty-description {
  font-size: 14px;
  color: #86909C;
  margin: 0;
}

.template-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 16px;
}

.template-item {
  border: 1px solid #E5E6EB;
  border-radius: 6px;
  padding: 16px;
  transition: all 0.3s;
}

.template-item:hover {
  border-color: #165DFF;
}

.template-title {
  font-size: 16px;
  font-weight: 500;
  color: #272E3B;
  margin: 0 0 8px 0;
}

.template-description {
  font-size: 14px;
  color: #86909C;
  margin: 0 0 16px 0;
  min-height: 40px;
}

.mr-2 {
  margin-right: 8px;
}

.ml-1 {
  margin-left: 4px;
}

.mb-4 {
  margin-bottom: 24px;
}
</style>
